package com.lyp.yangxixi.missionfragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.ajguan.library.EasyRefreshLayout;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lyp.activitys.CarDetailsClueActivity;
import com.lyp.activitys.DectionDetailsClueActivity;
import com.lyp.activitys.IndoorDetailsClueActivity;
import com.lyp.adapters.MAlltaskAdapter;
import com.lyp.jsonbean.LoginBean;
import com.lyp.jsonbean.MAllTaskBean;
import com.tjl.yangxixis.OriginalFragment;
import com.tjl.yangxixis.R;
import com.tjl.yangxixis.activity.MainActivity;
import com.tjl.yangxixis.api.YangxixiApi;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

//(我的任务)所有任务
public class AllMissionFragments extends OriginalFragment{
	View v;
	private RecyclerView mRecyclerView;
	private MAlltaskAdapter mAdapter;
	private LinearLayoutManager mLayoutManager;
	private List<MAllTaskBean.DataBean> mList = new ArrayList<>();
	private LoginBean.DataBean bean;
	private TextView mCounts;
	//定义一个页码为1
	int pages=1;
	private EasyRefreshLayout mEasyRefreshLayout;

	private int mPosition;

	public View createView(LayoutInflater inflater, ViewGroup container,
						   Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		v = inflater.inflate(R.layout.fragment_allmission, null,false);
		init();
		LogUtils.i("tag","11111111");
		return v;
	}

	public void init(){
		bean = ((MainActivity) getActivity()).dataBean;
		mCounts = (TextView) v.findViewById(R.id.tv_counts);
		mRecyclerView = (RecyclerView) v.findViewById(R.id.grid_recycler);
		mLayoutManager = new LinearLayoutManager(getActivity());
		mRecyclerView.setLayoutManager(mLayoutManager);
		mAdapter = new MAlltaskAdapter(mList);
		// 实例化 RecyclerView Adapter
		mRecyclerView.setAdapter(mAdapter);
		mAdapter.setOnItemClickListener(new MAlltaskAdapter.MyItemClickListener() {
			@Override
			public void onItemClick(View v, int position) {
                if(bean.getServer_select().equals("车内空气净化服务")){
					Intent intentcar = new Intent(getActivity(),CarDetailsClueActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("databean",mList.get(position));
					bundle.putInt("position", position);
					mPosition = position;
					LogUtils.i("tag",bean.getId());
					intentcar.putExtras(bundle);
					startActivityForResult(intentcar, 0x1010);
				}
				else if(bean.getServer_select().equals("第三方检测服务")){
					Intent intentdection = new Intent(getActivity(),DectionDetailsClueActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("databean",mList.get(position));
					bundle.putInt("position", position);
					mPosition = position;
					LogUtils.i("tag",bean.getId());
					intentdection.putExtras(bundle);
					startActivityForResult(intentdection, 0x1010);
				}
				else if(bean.getServer_select().equals("室内空气净化服务")){
					Intent intentindoor = new Intent(getActivity(),IndoorDetailsClueActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("databean",mList.get(position));
					bundle.putInt("position", position);
					mPosition = position;
					intentindoor.putExtras(bundle);
					startActivityForResult(intentindoor, 0x1010);
				}
			}
		});

		try {
			taskRefresh(bean.getId(),pages);
		} catch (IOException e) {
			e.printStackTrace();
		}

		mEasyRefreshLayout = (EasyRefreshLayout) v.findViewById(R.id.easylayout);
		mEasyRefreshLayout.addEasyEvent(new EasyRefreshLayout.EasyEvent() {
			@Override
			public void onLoadMore() {
				new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							taskLoadMore(bean.getId(),pages);
						} catch (IOException e) {
							e.printStackTrace();
						}
						getActivity().runOnUiThread(new Runnable() {
							@Override
							public void run() {
								mEasyRefreshLayout.loadMoreComplete();
							}
						});
					}
				}).start();
			}

			@Override
			public void onRefreshing() {
				new Thread(new Runnable() {
					@Override
					public void run() {
						SystemClock.sleep(1000);
						try {
							taskRefresh(bean.getId(),pages);
						} catch (IOException e) {
							e.printStackTrace();
						}
						getActivity().runOnUiThread(new Runnable() {
							@Override
							public void run() {
								mEasyRefreshLayout.refreshComplete();
							}
						});
					}
				}).start();
			}
		});

	}

	@Override
	protected void lazyLoad() {
		// TODO Auto-generated method stub
	}

	//刷新
	public void taskRefresh(String a_id,int page) throws IOException {
		Retrofit retrofit = new Retrofit.Builder()
				.baseUrl(YangxixiApi.APP_URL)
				.addConverterFactory(GsonConverterFactory.create())
				.build();
		YangxixiApi github = retrofit.create(YangxixiApi.class);
		Call<MAllTaskBean> call = github.getMAlltask(a_id,page);
		call.enqueue(new Callback<MAllTaskBean>() {
			@Override
			public void onResponse(Call<MAllTaskBean> call, final Response<MAllTaskBean> response) {
				if (response.body().getResult()== 1 ) {
					mCounts.setText(response.body().getCounts());
					getActivity().runOnUiThread(new Runnable() {
						@Override
						public void run() {
								mList.clear();
								mList.addAll(response.body().getData());
								mAdapter.notifyDataSetChanged();
							if (response.body().getNext_page() > 0) {
								pages++;
							} else {
								Toast.makeText(getActivity(),"没有更多数据了",Toast.LENGTH_SHORT).show();
							}
						}
					});
				}else {
					Toast.makeText(getActivity(),response.body().getMessage(),Toast.LENGTH_SHORT).show();
				}
			}
			@Override
			public void onFailure(Call<MAllTaskBean> call, Throwable t) {
				ToastUtils.showShort(t.getMessage());
			}
		});
	}

	//加载
	public void taskLoadMore(String a_id,int page) throws IOException {
		Retrofit retrofit = new Retrofit.Builder()
				.baseUrl(YangxixiApi.APP_URL)
				.addConverterFactory(GsonConverterFactory.create())
				.build();
		YangxixiApi github = retrofit.create(YangxixiApi.class);
		Call<MAllTaskBean> call = github.getMAlltask(a_id,page);
		call.enqueue(new Callback<MAllTaskBean>() {
			@Override
			public void onResponse(Call<MAllTaskBean> call, final Response<MAllTaskBean> response) {
				if (response.body().getResult()== 1 ) {
					mCounts.setText(response.body().getCounts());
					getActivity().runOnUiThread(new Runnable() {
						@Override
						public void run() {
							mList.clear();
							mList.addAll(response.body().getData());
							mAdapter.notifyDataSetChanged();
							if (pages >= 1) {
								pages--;
							} else {
								Toast.makeText(getActivity(),"没有更多数据了",Toast.LENGTH_SHORT).show();
							}
						}
					});
				}else {
					Toast.makeText(getActivity(),response.body().getMessage(),Toast.LENGTH_SHORT).show();
				}
			}
			@Override
			public void onFailure(Call<MAllTaskBean> call, Throwable t) {
				Toast.makeText(getActivity(),t.getMessage(),Toast.LENGTH_SHORT).show();
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == getActivity().RESULT_OK){
			try {
				taskRefresh(bean.getId(),pages);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else if (resultCode == 10011){
			switch (requestCode) {
				case 0x1010:
					mList.remove(mPosition);
					mCounts.setText(mList.size()+"");
					mAdapter.notifyDataSetChanged();
					break;
			}
		}
	}

}
